"""
MCP反馈增强服务
提供更高级的反馈处理和分析功能
"""

import time
from typing import Dict, Any, List, Optional
from src.services.mcp_service import mcp_service_manager
from src.utils.logging import get_logger

logger = get_logger(__name__)


class MCPFeedbackEnhancedService:
    """MCP反馈增强服务"""
    
    def __init__(self):
        self.feedback_categories = {
            "performance": {"weight": 2, "description": "性能相关反馈"},
            "error": {"weight": 3, "description": "错误相关反馈"},
            "suggestion": {"weight": 1, "description": "功能建议反馈"},
            "general": {"weight": 1, "description": "一般反馈"},
            "security": {"weight": 4, "description": "安全相关反馈"}
        }
        self.priority_levels = {
            "low": {"multiplier": 1, "description": "低优先级"},
            "medium": {"multiplier": 2, "description": "中优先级"},
            "high": {"multiplier": 3, "description": "高优先级"},
            "critical": {"multiplier": 5, "description": "紧急优先级"}
        }
    
    def add_enhanced_feedback(self, server_name: str, user_id: str, feedback: str, 
                             feedback_type: str = "general", priority: str = "medium",
                             metadata: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """
        添加增强型反馈
        
        Args:
            server_name: 服务器名称
            user_id: 用户ID
            feedback: 反馈内容
            feedback_type: 反馈类型
            priority: 优先级 (low, medium, high, critical)
            metadata: 元数据
            
        Returns:
            添加结果
        """
        try:
            # 验证反馈类型
            if feedback_type not in self.feedback_categories:
                return {
                    "success": False,
                    "error": f"无效的反馈类型: {feedback_type}"
                }
            
            # 验证优先级
            if priority not in self.priority_levels:
                return {
                    "success": False,
                    "error": f"无效的优先级: {priority}"
                }
            
            # 添加反馈到基础服务
            base_result = mcp_service_manager.add_feedback(
                server_name=server_name,
                user_id=user_id,
                feedback=feedback,
                feedback_type=feedback_type,
                metadata=metadata,
                priority=priority
            )
            
            if not base_result["success"]:
                return base_result
            
            return {
                "success": True,
                "message": "增强反馈已成功记录",
                "feedback_id": base_result["feedback_id"]
            }
        except Exception as e:
            logger.error(f"添加增强反馈失败: {e}")
            return {
                "success": False,
                "error": f"添加增强反馈失败: {str(e)}"
            }
    
    def analyze_feedback_patterns(self, server_name: str, days: int = 7) -> Dict[str, Any]:
        """
        分析反馈模式
        
        Args:
            server_name: 服务器名称
            days: 分析天数
            
        Returns:
            反馈模式分析结果
        """
        try:
            # 获取反馈历史
            feedback_history = mcp_service_manager.get_feedback_history(server_name)
            
            if not feedback_history:
                return {
                    "success": True,
                    "server_name": server_name,
                    "message": "没有反馈数据可供分析"
                }
            
            # 筛选指定时间范围内的反馈
            now = time.time()
            period_start = now - (days * 24 * 60 * 60)
            recent_feedback = [
                f for f in feedback_history 
                if f.get('timestamp', 0) >= period_start
            ]
            
            if not recent_feedback:
                return {
                    "success": True,
                    "server_name": server_name,
                    "message": f"最近{days}天内没有反馈数据"
                }
            
            # 模式分析
            analysis = {
                "total_feedback": len(recent_feedback),
                "feedback_by_type": {},
                "feedback_by_priority": {},
                "recurring_issues": [],
                "escalation_patterns": []
            }
            
            # 按类型和优先级统计
            for feedback in recent_feedback:
                # 类型统计
                fb_type = feedback.get("feedback_type", "general")
                analysis["feedback_by_type"][fb_type] = analysis["feedback_by_type"].get(fb_type, 0) + 1
                
                # 优先级统计（如果存在）
                priority = feedback.get("priority", "medium")
                analysis["feedback_by_priority"][priority] = analysis["feedback_by_priority"].get(priority, 0) + 1
            
            # 识别重复问题
            feedback_texts = [f.get("feedback", "") for f in recent_feedback]
            unique_texts = set(feedback_texts)
            
            for text in unique_texts:
                count = feedback_texts.count(text)
                if count > 2:  # 如果同一反馈出现3次以上，认为是重复问题
                    analysis["recurring_issues"].append({
                        "issue": text[:100] + "..." if len(text) > 100 else text,
                        "occurrences": count
                    })
            
            # 识别升级模式（从低优先级到高优先级的反馈）
            high_priority_count = analysis["feedback_by_priority"].get("high", 0) + analysis["feedback_by_priority"].get("critical", 0)
            if high_priority_count > len(recent_feedback) * 0.3:  # 高优先级反馈超过30%
                analysis["escalation_patterns"].append("高优先级反馈比例较高")
            
            return {
                "success": True,
                "server_name": server_name,
                "analysis_period_days": days,
                "analysis": analysis
            }
        except Exception as e:
            logger.error(f"分析反馈模式失败: {e}")
            return {
                "success": False,
                "error": f"分析反馈模式失败: {str(e)}"
            }
    
    def prioritize_feedback_queue(self, server_name: str) -> List[Dict[str, Any]]:
        """
        对反馈队列进行优先级排序
        
        Args:
            server_name: 服务器名称
            
        Returns:
            按优先级排序的反馈列表
        """
        try:
            # 获取所有未处理的反馈
            feedback_history = mcp_service_manager.get_feedback_history(server_name)
            unprocessed_feedback = [
                f for f in feedback_history 
                if not f.get('processed', False)
            ]
            
            # 计算每个反馈的优先级分数
            for feedback in unprocessed_feedback:
                feedback_type = feedback.get("feedback_type", "general")
                priority = feedback.get("priority", "medium")
                
                # 计算优先级分数
                type_weight = self.feedback_categories.get(feedback_type, {"weight": 1})["weight"]
                priority_multiplier = self.priority_levels.get(priority, {"multiplier": 1})["multiplier"]
                
                feedback["priority_score"] = type_weight * priority_multiplier
            
            # 按优先级分数排序
            sorted_feedback = sorted(
                unprocessed_feedback, 
                key=lambda x: x.get("priority_score", 0), 
                reverse=True
            )
            
            return sorted_feedback
        except Exception as e:
            logger.error(f"优先级排序反馈失败: {e}")
            return []
    
    def generate_action_plan(self, server_name: str) -> Dict[str, Any]:
        """
        生成基于反馈的行动方案
        
        Args:
            server_name: 服务器名称
            
        Returns:
            行动方案
        """
        try:
            # 获取优先级排序的反馈
            prioritized_feedback = self.prioritize_feedback_queue(server_name)
            
            if not prioritized_feedback:
                return {
                    "success": True,
                    "message": "没有需要处理的反馈",
                    "action_items": []
                }
            
            # 生成行动项
            action_items = []
            processed_types = set()
            
            for feedback in prioritized_feedback[:10]:  # 只处理前10个最高优先级的反馈
                feedback_type = feedback.get("feedback_type", "general")
                priority = feedback.get("priority", "medium")
                feedback_text = feedback.get("feedback", "")
                
                # 避免重复的行动项
                if feedback_type in processed_types:
                    continue
                
                action_item = {
                    "feedback_type": feedback_type,
                    "priority": priority,
                    "description": self.feedback_categories[feedback_type]["description"],
                    "recommended_action": self._get_recommended_action(feedback_type),
                    "sample_feedback": feedback_text[:100] + "..." if len(feedback_text) > 100 else feedback_text,
                    "count": len([f for f in prioritized_feedback if f.get("feedback_type") == feedback_type])
                }
                
                action_items.append(action_item)
                processed_types.add(feedback_type)
            
            return {
                "success": True,
                "server_name": server_name,
                "action_items": action_items,
                "total_prioritized_feedback": len(prioritized_feedback)
            }
        except Exception as e:
            logger.error(f"生成行动方案失败: {e}")
            return {
                "success": False,
                "error": f"生成行动方案失败: {str(e)}"
            }
    
    def _get_recommended_action(self, feedback_type: str) -> str:
        """
        根据反馈类型获取推荐操作
        
        Args:
            feedback_type: 反馈类型
            
        Returns:
            推荐操作
        """
        recommendations = {
            "performance": "优化服务器性能配置，增加资源分配",
            "error": "检查并修复相关错误，增加错误处理机制",
            "suggestion": "评估功能建议的可行性，制定开发计划",
            "general": "收集更多用户反馈，改进用户体验",
            "security": "立即审查安全配置，修复安全漏洞"
        }
        
        return recommendations.get(feedback_type, "评估反馈内容，制定相应解决方案")
    
    def export_feedback_insights(self, server_name: str, format: str = "json") -> Dict[str, Any]:
        """
        导出反馈洞察报告
        
        Args:
            server_name: 服务器名称
            format: 导出格式 (json, text)
            
        Returns:
            导出的洞察报告
        """
        try:
            # 获取各种分析数据
            summary = mcp_service_manager.get_feedback_summary(server_name)
            # 注意：这里需要确保mcp_service_manager中有analyze_feedback_trends方法
            # 如果没有，我们需要添加它或者使用其他方式获取趋势数据
            
            # 模拟趋势分析数据（实际应调用真实方法）
            trends = {
                "server_name": server_name,
                "analysis_period_days": 7,
                "total_feedback": summary.get("total_feedback", 0),
                "feedback_by_type": summary.get("feedback_by_type", {}),
                "average_daily_feedback": summary.get("total_feedback", 0) / 7,
                "trend": "stable"
            }
            
            patterns = self.analyze_feedback_patterns(server_name)
            action_plan = self.generate_action_plan(server_name)
            
            insights_data = {
                "server_name": server_name,
                "generated_at": time.time(),
                "summary": summary,
                "trends": trends,
                "patterns": patterns,
                "action_plan": action_plan
            }
            
            if format.lower() == "json":
                return {
                    "success": True,
                    "format": "json",
                    "data": insights_data
                }
            else:  # text format
                # 生成文本报告
                text_report = f"""
MCP服务反馈洞察报告
====================
服务器名称: {server_name}
生成时间: {time.ctime(insights_data['generated_at'])}

摘要信息:
- 总反馈数: {summary.get('total_feedback', 0)}
- 按类型统计: {summary.get('feedback_by_type', {})}

趋势分析:
- 分析周期: {trends.get('analysis_period_days', 0)} 天
- 总反馈数: {trends.get('total_feedback', 0)}
- 日均反馈数: {trends.get('average_daily_feedback', 0):.2f}
- 趋势: {trends.get('trend', 'unknown')}

模式分析:
- 重复问题: {patterns.get('analysis', {}).get('recurring_issues', [])}
- 升级模式: {patterns.get('analysis', {}).get('escalation_patterns', [])}

行动方案:
"""
                for item in action_plan.get('action_items', []):
                    text_report += f"""
- 类型: {item['feedback_type']}
  优先级: {item['priority']}
  推荐操作: {item['recommended_action']}
  相关反馈数: {item['count']}
"""
                
                return {
                    "success": True,
                    "format": "text",
                    "data": text_report
                }
        except Exception as e:
            logger.error(f"导出反馈洞察失败: {e}")
            return {
                "success": False,
                "error": f"导出反馈洞察失败: {str(e)}"
            }


# 创建服务实例
mcp_feedback_enhanced_service = MCPFeedbackEnhancedService()

# 导出
__all__ = ["MCPFeedbackEnhancedService", "mcp_feedback_enhanced_service"]